//
//  PeiDetailsVC.m
//  JinChengYun
//
//  Created by 金橙云 on 2017/3/24.
//  Copyright © 2017年 金橙云. All rights reserved.
//

#import "PeiDetailsVC.h"

#import "TodoHttpManager.h"
#import "RKTagsMenuView.h"//表头
#import "CustomCollectionViewCell.h"
#import "PeiLastXVC.h"

#import "MJRefresh.h"
@interface PeiDetailsVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSArray *_unitArr;
    NSDictionary *_nameDic;
    NSMutableArray *_busXArr;
    NSString *_louStr;
    //NSMutableArray *_oneArr;
    NSMutableDictionary *_firstDic;
    NSString *IDA;
    
     NSMutableDictionary *cell_IdDic;//存放cell唯一标识符
     NSString *identifier_yi;
    
    NSString *_newZong;
    NSString *_newYi;
    NSString *_newWei;
    
    NSString *_peiSeleUnit;
}

@property (nonatomic, strong) NSMutableArray *twoArr;
@property (nonatomic,strong) NSMutableArray *qiArr;
@property (nonatomic,strong) NSMutableArray *qiIDArr;
@property(nonatomic,strong)UICollectionView *collectView;

@end

@implementation PeiDetailsVC

-(void)viewWillAppear:(BOOL)animated
{
    
    //表头通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDZhuSBiaoTou:) name:TDZhuSBiaoTou object:nil];
    
    //房源(配套/商业)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDZhuSHouse:) name:TDZhuSHouse object:nil];
    
    
    if (_unitArr.count == 0)
    {
        if ([_houseID isEqualToString:@"车位"])
        {
          
            //TODO:表头
            [_manager userZhuShouHouseBiaoWithType:@"2" withQiShu:_qID];
              [_collectView reloadData];

        }
        else
        {
             [_manager userZhuShouHouseBiaoWithType:@"4" withQiShu:_qID];
              [_collectView reloadData];
        }

        
        
    }
    
    
    
}

//表头通知方法
-(void)didTDZhuSBiaoTou:(NSNotification *)notifi
{
    if (notifi.object != 0)
    {
        int status = [[notifi.object objectForKey:@"status"] intValue];
        if (status == 1)
        {
            _unitArr = [notifi.object objectForKey:@"data"];
            
            _firstDic = [_unitArr objectAtIndex:0];
            _louStr = [_firstDic objectForKey:@"id"];
          // NSLog(@"=======  99999 %@",_louStr);
            
            for (int i = 0; i < _unitArr.count; i++) {
                
                NSDictionary *dict = [_unitArr objectAtIndex:i];
                [_qiArr addObject:dict[@"name"]];
                [_qiIDArr addObject:dict[@"id"]];
                
            }
                  [_collectView reloadData];
            [self setupMenuQiArr:_qiArr];
      
            [super viewDidLoad];
          
            
        }
     
    }
    
    
}

//房源(配套/商业)
-(void)didTDZhuSHouse:(NSNotification *)noti
{
    if (noti.object != 0)
    {
        _newZong = [noti.object objectForKey:@"all_rooms"];
        _newYi = [noti.object objectForKey:@"sale_rooms"];
        _newWei = [noti.object objectForKey:@"rest_rooms"];
        int status = [[noti.object objectForKey:@"status"] intValue];
        if (status == 1)
        {
 
            [_twoArr addObjectsFromArray:[noti.object objectForKey:@"data"]];
            
     
             [self setPeiTaoTOP];
              [_collectView reloadData];
            [super viewDidLoad];
        }
        else
        {
            //[_manager MakeMyselfAlert:@"获取失败" andIsNeedTitle:NO andShowTime:2.0];
        }
    }
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    //移除表头通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TDZhuSBiaoTou object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TDZhuSHouse object:nil];
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
   self.title = @"房源管理";
    self.view.backgroundColor = BgColor;
    
    NSLog(@"--------%@-------%@",_qID,_houseID);
    cell_IdDic = [NSMutableDictionary new];
    
    
    _manager = [TodoHttpManager sharedManager];
    IDA = [[NSUserDefaults standardUserDefaults] objectForKey:@"STATE"];
   
    _unitArr = [NSArray array];
    _nameDic = [NSDictionary dictionary];
    _busXArr = [[NSMutableArray alloc] init];
    _qiArr = [[NSMutableArray alloc] init];
    _twoArr = [[NSMutableArray alloc] init];
    _firstDic = [[NSMutableDictionary alloc] init];
    _qiIDArr = [[NSMutableArray alloc] init];
    //布局对象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    flowLayout.itemSize = CGSizeMake((B_WIDTH-30)/3,40);
    
    flowLayout.headerReferenceSize = CGSizeMake(0, 30);//头部
  
    // 内容 与控件四周的距离
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    _collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight+30+44, B_WIDTH, B_HEIGHT-140)collectionViewLayout:flowLayout];
    _collectView.backgroundColor = BgColor;
    _collectView.delegate = self;
    _collectView.dataSource = self;
    [self.view addSubview:_collectView];
    //TODO:注册cell
    [_collectView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    


    //注册头视图
    [_collectView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeaderPeiTao"];
    
    [self setupMenuQiArr:_qiArr];
    

     self.collectView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(peiTaoheaderTageAction)];
   
}

-(void)peiTaoheaderTageAction
{
    [self peiTaoRefresh];
   // [self setupMenuQiArr:_qiArr];
 
    [_collectView.mj_header endRefreshing];
}


-(void)setPeiTaoTOP
{
    UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, B_WIDTH, 30)];
    aView.backgroundColor = [UIColor colorWithHexString:@"#eb6200"];
    [self.view addSubview:aView];
    
    UILabel *oneLab = [[UILabel alloc] init];
    oneLab.text = [NSString stringWithFormat:@"总房源 :%@套",_newZong.length>0?_newZong:@""];
    oneLab.textColor = [UIColor whiteColor];
    oneLab.font = [UIFont systemFontOfSize:12];
    [aView addSubview:oneLab];
    [oneLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 20));
        make.left.equalTo(aView.mas_left).offset(20);
        make.top.equalTo(aView.mas_top).offset(5);
        
    }];
    
    UILabel *twoLab = [[UILabel alloc] init];
    twoLab.text = [NSString stringWithFormat:@"已售 :%@套",_newYi.length>0?_newYi:@""];
    twoLab.textColor = [UIColor whiteColor];
    twoLab.font = [UIFont systemFontOfSize:12];
    [aView addSubview:twoLab];
    [twoLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 20));
        make.left.equalTo(oneLab.mas_right).offset(10);
        make.top.equalTo(aView.mas_top).offset(5);
        
    }];
    
    UILabel *sanLab = [[UILabel alloc] init];
    sanLab.text = [NSString stringWithFormat:@"未售 :%@套",_newWei.length>0?_newWei:@""];
    sanLab.textColor = [UIColor whiteColor];
    sanLab.font = [UIFont systemFontOfSize:12];
    [aView addSubview:sanLab];
    [sanLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 20));
        make.left.equalTo(twoLab.mas_right).offset(10);
        make.top.equalTo(aView.mas_top).offset(5);
        
    }];
}

-(void)peiTaoRefresh
{

    if ([_houseID isEqualToString:@"车位"])
    {

        [_manager userZhuShouFangYuanWithType:@"2" withQi:_qID withQuYU:_peiSeleUnit withLou:nil];
        [cell_IdDic removeAllObjects];
        [_collectView reloadData];

    }
    else
    {


        //TODO:表头
        [_manager userZhuShouFangYuanWithType:@"4" withQi:_qID withQuYU:nil withLou:_peiSeleUnit];

        [cell_IdDic removeAllObjects];

        [_collectView reloadData];
    }

}
-(void)setupMenuQiArr:(NSMutableArray *)qiArr
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    RKTagsMenuView *tagMenuView = [[RKTagsMenuView alloc] initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight+30,self.view.frame.size.width, 44)];
    tagMenuView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:tagMenuView];
    [tagMenuView setTagsArray:qiArr];
    

    if ([_houseID isEqualToString:@"车位"])
    {
 
       [_manager userZhuShouFangYuanWithType:@"2" withQi:_qID withQuYU:_louStr withLou:nil];
        [_collectView reloadData];
        
    }else
    {
       
        //TODO:表头
        [_manager userZhuShouFangYuanWithType:@"4" withQi:_qID withQuYU:nil withLou:_louStr];
         [_collectView reloadData];
    }

    [tagMenuView setDidSelectTagBlock:^(NSInteger clickedRow) {
        
        _louStr = _qiIDArr[clickedRow];
        if (_twoArr.count > 0)
        {
        
            [_twoArr removeAllObjects];
           
        }
        
        NSLog(@"点击了 %@", qiArr[clickedRow]);
        
        if ([_houseID isEqualToString:@"车位"])
        {
            
            [_manager userZhuShouFangYuanWithType:@"2" withQi:_qID withQuYU:_louStr withLou:nil];
            [cell_IdDic removeAllObjects];
            [_collectView reloadData];
            
        }
        else
        {
       

            //TODO:表头
            [_manager userZhuShouFangYuanWithType:@"4" withQi:_qID withQuYU:nil withLou:_louStr];
            
            [cell_IdDic removeAllObjects];
            
            [_collectView reloadData];
        }

     
    }];
    
    
}

#pragma mark - UICollectionViewDelegate&&DateSoucre


//创建头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *oneView = [ collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeaderPeiTao"forIndexPath:indexPath];
    
    
    NSInteger aa = (B_WIDTH-300)/4;
    
    oneView.backgroundColor = BgColor;
    [self.view addSubview:oneView];
    
    UIButton *redBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    redBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [redBtn setTitleColor:[UIColor blackColor] forState:0];
    [redBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [redBtn setImage:[UIImage imageNamed:@"Color_yishou"] forState:0];
    [redBtn setTitle:@"已售" forState:0];
    [oneView addSubview:redBtn];
    [redBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(55, 20));
        make.left.equalTo(oneView.mas_left).offset(6);
        make.top.equalTo(oneView.mas_top).offset(5);
    }];
    
    UIButton *writeBrn = [UIButton buttonWithType:UIButtonTypeCustom];
    writeBrn.titleLabel.font = [UIFont systemFontOfSize:10];
    [writeBrn setTitleColor:[UIColor blackColor] forState:0];
    [writeBrn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [writeBrn setImage:[UIImage imageNamed:@"Color_bai"] forState:0];
    [writeBrn setTitle:@"未售" forState:0];
    [oneView addSubview:writeBrn];
    [writeBrn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(55, 20));
        make.left.equalTo(redBtn.mas_right).offset(aa);
        make.top.equalTo(oneView.mas_top).offset(5);
    }];
    
    UIButton *blueBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    blueBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [blueBtn setTitleColor:[UIColor blackColor] forState:0];
    [blueBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [blueBtn setImage:[UIImage imageNamed:@"Color_blue"] forState:0];
    [blueBtn setTitle:@"抵押融资" forState:0];
    [oneView addSubview:blueBtn];
    [blueBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 20));
        //make.left.equalTo(oneView.mas_left).offset(6);
        make.top.equalTo(oneView.mas_top).offset(5);
        make.centerX.equalTo(oneView.mas_centerX);
    }];
    
    
    UIButton *greenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    greenBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [greenBtn setTitleColor:[UIColor blackColor] forState:0];
    [greenBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [greenBtn setImage:[UIImage imageNamed:@"Color_lv"] forState:0];
    [greenBtn setTitle:@"内留" forState:0];
    [oneView addSubview:greenBtn];
    [greenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 20));
        make.left.equalTo(blueBtn.mas_right).offset(aa);
        make.top.equalTo(oneView.mas_top).offset(5);
        
    }];
    
    
    UIButton *grayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    grayBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    [grayBtn setTitleColor:[UIColor blackColor] forState:0];
    [grayBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:7];
    [grayBtn setImage:[UIImage imageNamed:@"Color_zi"] forState:0];
    [grayBtn setTitle:@"调房待批" forState:0];
    [oneView addSubview:grayBtn];
    [grayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 20));
        make.right.equalTo(oneView.mas_right).offset(-6);
        make.top.equalTo(oneView.mas_top).offset(5);
        
    }];
    

    return oneView;
}

// 设置section头视图的参考大小，与tableheaderview类似
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section
{
    
    
    if ([IDA isEqualToString:@"1"])
    {
        return CGSizeMake(0, 0);
    }
    else
    {
        if (section == 0) {
            return CGSizeMake(self.view.frame.size.width,30);
        }
        else {
            return CGSizeMake(0, 0);
        }
        
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _twoArr.count>0?_twoArr.count:0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
//    // 每次先从字典中根据IndexPath取出唯一标识符，避免复用
//    identifier_yi = [cell_IdDic objectForKey:[NSString stringWithFormat:@"%ld", indexPath.item]];
//    // 如果取出的唯一标示符不存在，则初始化唯一标示符，并将其存入字典中，对应唯一标示符注册Cell
//    if (identifier_yi == nil)
//    {
//        identifier_yi = [NSString stringWithFormat:@"PeiCollectionCell%@",[NSString stringWithFormat:@"%ld", indexPath.item]];
//        [cell_IdDic setValue:identifier_yi forKey:[NSString stringWithFormat:@"%ld", indexPath.item]];
//        // 注册Cell
//        [_collectView registerClass:[CustomCollectionViewCell class]  forCellWithReuseIdentifier:identifier_yi];
//
//    }
    
    //单元格初始化
    CustomCollectionViewCell *cell =(CustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
 
    if ([cell isKindOfClass:[CustomCollectionViewCell class]])
    {
        
        if (_twoArr.count != 0)
        {
            NSDictionary *dict = [_twoArr objectAtIndex:indexPath.row];
            [(CustomCollectionViewCell *)cell setupCollectionViewWithStatus:dict[@"is_sale"]];
//            cell.titleLab.text = [dict objectForKey:@"room_num"];
            [cell.statusBtn setTitle:[dict objectForKey:@"room_num"] forState:UIControlStateNormal];
            cell.statusBtn.tag = indexPath.row;
            //  NSLog(@"==%@",dict[@"is_sale"]);
            [cell setupCollectionViewWithStatus:[NSString stringWithFormat:@"%@",dict[@"is_sale"]] ];
        }
    }
    //找到每一个按钮；
    
    UIButton*deviceImageButton = cell.statusBtn;
    [deviceImageButton addTarget:self action:@selector(deviceButtonPressed:)
                forControlEvents:UIControlEventTouchUpInside];
    
    
    
    return cell;
    
}
-(void)deviceButtonPressed:(id)sender
{
    
   // UIView *v = [sender superview];//获取父类view
    CustomCollectionViewCell *cell = (CustomCollectionViewCell *)[sender superview];//获取cell
    NSIndexPath *indexpath = [self.collectView indexPathForCell:cell];//获取cell对应的indexpath;
    
    NSLog(@"设备图片按钮被点击:%ld%ld",(long)indexpath.section,(long)indexpath.row);
    
    PeiLastXVC *peiLVC = [[PeiLastXVC alloc] init];
    peiLVC.IDStr =[[_twoArr objectAtIndex:indexpath.section]objectForKey:@"uid"];
    peiLVC.saleStr = [[_twoArr objectAtIndex:indexpath.section]objectForKey:@"is_sale"];
   // NSLog(@"这是什么1111111-----------输出的是%@",[[_oneArr objectAtIndex:indexpath.section]objectForKey:@"is_sale"]);
    [self.navigationController pushViewController:peiLVC animated:NO];
    
    
    
}



    
    






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
